/*
 * serial_com.c
 *
 *  Created on: 07.02.2014
 *      Author: Gigi
 */
#include<a_nRF24L01.h>
#include <serial_com.h>




/* Serial send data */
void serial_com_USART_send(unsigned char data)
{
/* The first line is a bit odd, but it as its reasons,
 * that line is checking if there is space in the Atmega
 * send buffer(the atmega chip as a small 3 byte hardware
 * buffer in the TX/send channel) to put a new char/byte,
 * if yes the char/byte is loaded into the UDR0 register
 * which makes part of the USART hardware and if something
 * is loaded into that register it will be sent by the USART */

	while(!(UCSR0A & (1<<UDRE0)));
	UDR0 = data;
}



/* will send the string for the given string address */
void serial_com_USART_put_string(char * ptr_to_String)
{
	while(*ptr_to_String != 0x00)
	{
		serial_com_USART_send(*ptr_to_String);
		ptr_to_String++;
	}
}



/* Serial receive data */
unsigned char serial_com_USART_receive(void)
{
/* In the first line the while loop is used to
 * pool the receive register, and if there is
 * new data in that register we return the data */

	unsigned char incoming_byte = 0xFF;

	if((UCSR0A & (1<<RXC0)))
		incoming_byte = UDR0;
	else
		incoming_byte = 0xFF;

return incoming_byte;
}


void serial_com_USART_flush()
{
	unsigned char dummy;
	while(UCSR0A & (1<<RXC0)) dummy = UDR0;
}

void serial_com_echo_function()
{
	unsigned char incoming = serial_com_USART_receive();

	if(incoming == 0xFF)
	{

	}
	else
	{
		serial_com_USART_send(incoming);
	}
}

/* Serial port initialization */
void serial_com_USART_init()
{
	/* UBRR0H and UBRR0L represents the baud-rate */
	UBRR0H = (uint8_t)(BAUD_PRESCALLER>>8);
	UBRR0L = (uint8_t)(BAUD_PRESCALLER	 );

	/* UCSR0B is the register for control of Rx(RXEN0) and TX(TXEN0) */
	UCSR0B = (1<<RXEN0)|(1<<TXEN0);
	/* UCSZ00 and UCZS01 bits */
	UCSR0C = (3<<UCSZ00)|(1<<USBS0);
}
